<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\models\{Region, Cate, Subcate, Product, Banner, Cart, Config, Wechat, Annous, Riderlist, Promo, Agent, AgentArea, Address};
use think\facade\Env;
use think\Db;
use oss\Oss;
use think\facade\Log;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{


    public function annous()
    {

        $list = (new Annous())->where(['agentid' => [$this->request->user['agentid'], 0]])->order('id desc')->field('id,title,types,content')->select();
        $this->result($list, 0, '获取成功');
    }

    public function getconfig()
    {
        $name = $this->request->get('name/s', 0);
        $list = (new Config())->where('name', $name)->value('value') ?? '';
        $this->result($list, 0, '获取成功');
    }

    public function banner()
    {
        $list = (new Banner())->order('sort desc')->where(['agentid' => $this->request->user['agentid']])->field('id,title,url,appid');
        $list = $list->select();
        $this->result($list, 0, '获取成功');
    }

    public function oss()
    {
        if ($this->request->isPost()) {
            if (Env::get('aliyun.open')) {
                $file =  $_FILES['file'] ?? '';
                if (empty($file)) {
                    $this->result([], 1, '请选择上传图片');
                }
                $oss = new Oss();
                $oss->setUploadType('ram');
                $url = $oss->uploadPostFile($file, 'duangduang/' . date('Y-m-d'));
                $this->result($url, 0, '获取成功');
                $result = [];
                try {
                    $result = (new Oss())->getCredentials();
                    $result['regionId'] = Env::get('aliyun.regionId');
                    $result['bucket'] = Env::get('aliyun.bucket');
                    $result['endpoint'] = Env::get('aliyun.endpoint');
                } catch (\Exception $e) {
                    $this->result([], 1, $e->getMessage());
                }
                $this->result($result, 0, '获取成功');
            } else {
                $file = request()->file('file');
                $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
                $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])
                    ->move($path);
                if (!$info) {
                    $this->result([], 1, $file->getError());
                } else {
                    $file_edit = $info->getInfo();
                    $url = './uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                    if ($file_edit['size'] > 204800) { // 大于100K的图片进行处理
                        // 获取上传的图片，进行图片压缩
                        $image = \think\Image::open($info);
                        // 保存图片的路径处理
                        $image->thumb(1400, 1400)->save($url);
                    }
                    $url = url($url, '', '', false);
                    $url = "https://" . Env('app.api_url') . $url;
                    $this->result($url, 0, '获取成功');
                }
            }
        }
    }

    //获取商家信息
    public function agentinfo()
    {
        $agentid = $this->request->get('agentid/d', 0);
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $resuls = (new Agent())
            ->where('id', $agentid)
            ->field('id,nickname,payopen,send,maxkm,starsendmoney,address,mobile,psmoney,lat,lon,' . $filed)
            ->find();
        if ($resuls) {
            $resuls['chao'] = 1;
            $resuls['psmoney'] = (float)($resuls['psmoney'] ?? 0);
            $resuls['maxkm'] = (float)($resuls['maxkm'] ?? 0);
            $resuls['dist'] = (float)($resuls['dist'] ?? 0);
            $resuls['starsendmoney'] = (float)($resuls['starsendmoney'] ?? 0);
            if ($resuls['maxkm'] < $resuls['dist']) {
                $resuls['chao'] = 2;
            }
        }
        $this->result($resuls, 0, '获取成功');
    }

    //高德接口
    public function getstreet()
    {
        $key = env('map.key');
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['getstore'])) {
                $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $data['lat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $data['lat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $data['lng'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
                $business = (new Agent())
                    ->field('id,nickname,send,' . $filed)
                    ->order('dist asc')
                    // ->having('dist <= sendkm')
                    ->find();
                $resuls['agentid'] = $business['id'] ?? 0;
                $resuls['agent_name'] = $business['nickname'] ?? '暂无门店';
                $this->result($resuls, 0, '获取成功');
            }
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败,请重试');
                }
                $results = $res['regeocode']['addressComponent'];
                //街道查不到重新请求
                if (empty($results['township'])) {
                    $data['lng'] = floor($data['lng'] * 10000) / 10000;
                    $data['lat'] = floor($data['lat'] * 10000) / 10000;
                    $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
                    if ($res['status'] == 1) {
                        if (empty($res['regeocode']['addressComponent'])) {
                            $this->result([], 1, '请求失败,请重试');
                        }
                        $results = $res['regeocode']['addressComponent'];
                    }
                }
                $add = $res['regeocode']['aois'][0]['name'] ?? '';
                if (empty($add)) {
                    $add = $res['regeocode']['pois'][0]['name'] ?? '';
                }
                $resuls = [
                    "adcode" => !empty($results['adcode']) ? $results['adcode'] : 0,
                    "province" => !empty($results['province']) ? $results['province'] : '未知省份',
                    "city" => !empty($results['city']) ? $results['city'] : '未知城市',
                    "district" => !empty($results['district']) ? $results['district'] : '未知区域',
                    "street" => 0,
                    "agentid" => 0,
                    "street_title" => !empty($results['township']) ? $results['township'] : '未知街道',
                    'address' => $add ?? '',
                    'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
                ];
                $results['towncode'] = !empty($results['towncode']) ? $results['towncode'] : 0;
                $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
                //长名字查找不到 缩减名字查找
                $township = mb_substr($resuls['street_title'], 0, 2, 'utf-8');
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('name|remark', 'like', '%' . $township . '%')->find();
                }
                //通过名字查找不到街道再通过编号查找
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('code', substr($results['towncode'] ?? 0, 0, 9))->find();
                }
                $resuls['street'] = $street_id['id'] ?? 0;
                $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
                // //插入街道
                if (empty($resuls['street']) && !empty($resuls['adcode'])) {
                    $insertregion = (new Region())->where(['level' => 3, 'area_code' => $resuls['adcode']])->value('id');
                    if ($insertregion > 0) {
                        $resuls['street'] = (new Region())->insertGetId(
                            [
                                'parent_id' => $insertregion,
                                'level' => 4,
                                'name' => $resuls['street_title'],
                                'area_code' => $resuls['adcode'],
                                'code' => $resuls['adcode'] * 1000
                            ]
                        );
                    }
                }
                Log::write($resuls, 'getstreet');
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 0, ['key' => $key]);
        }
    }

    public function street()
    {
        $areacode = $this->request->get('areacode/d', 0);
        $list = (new Region())->where('area_code', $areacode)->where(['level' => 4])->select();
        $this->result($list, 0, '获取成功');
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }

    public function cate()
    {
        $list =  (new Cate())->where(['agentid' => $this->request->user['agentid']])->order(['sort' => 'desc', 'id' => 'desc'])->where(['isshow' => 1])->field('id,name,images')->select();
        $this->result($list, 0, '获取成功');
    }

    public function subcate()
    {
        $agentid = $this->request->user['agentid'];
        $cate = $this->request->get('cate/d', 0);
        $page = $this->request->get('page/d', 1);
        $keyword = $this->request->get('keyword/s', '');
        $menus =  (new Cate())
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->where(['isshow' => 1, 'agentid' => $agentid])->field('id,name');
        $menus = $menus->select();
        $result[0] = [
            'id' => 0,
            'name' => '全部',
        ];
        $result[1] = [
            'id' => 99999999,
            'name' => '新品',
        ];
        foreach ($menus as $k => $row) {
            $result[$k + 2] = $row;
        }
        $user_id = $this->request->user_id ? $this->request->user_id : 0;
        $result = ['menus' => $result];
        //全部产品
        $productss = (new Product())->alias('p')
            ->order(['p.sort' => 'desc', 'p.id' => 'desc'])
            ->leftjoin('cart c', ['c.user_id = ' . $user_id, 'c.productid = p.id'])
            ->where(['p.isdel' => 1, 'p.isshow' => 1, 'p.isremove' => 1, 'p.agentid' => $agentid])
            ->limit(15)
            ->page($page)
            ->field('p.id,p.title,p.inventory,p.parame,p.descs,p.images,p.price,ifnull(c.id,0) as cartid,ifnull(c.number,0) as number');
        if (!empty($cate) && $cate == 99999999) {
            $productss = $productss->where('p.isnew', 2);
        }
        if (!empty($cate) && $cate != 99999999) {
            $productss = $productss->where('p.cate', $cate);
        }
        if (!empty($keyword)) {
            $productss = $productss->where('p.title', 'like', '%' . $keyword . '%');
        }
        $productss = $productss->select();
        foreach ($productss as $product) {
            $product['parame'] = json_decode($product['parame'], true) ?? [];
            try {
                if (!empty($product['images'])) {
                    $parsedUrl = parse_url($product['images']);
                    $filename = basename($product['images']);
                    $file = './yasuo/' . $filename;
                    if (!file_exists($file)) {
                        $image = \think\Image::open('.' . $parsedUrl['path']);
                        $sturl = './yasuo' . '/' . $filename;
                        $turl = '/yasuo' . '/' . $filename;
                        $image->thumb(750, 750)->save($sturl, 'jpeg', 70);
                        $product['images'] = "https://" . Env('app.api_url') . $turl;
                    } else {
                        $sturl = '/yasuo' . '/' . $filename;
                        $product['images'] = "https://" . Env('app.api_url') . $sturl;
                    }
                }
            } catch (\Exception $e) {
            }
        }
        $result['data'] = $productss;
        $this->result($result, 0, '获取成功');
    }

    public function subcate1()
    {
        $agentid = $this->request->user['agentid'];
        $cate = $this->request->get('cate/d', 0);
        $list =  (new Cate())
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->where(['isshow' => 1, 'agentid' => $agentid])->field('id,name');
        if (!empty($cate)) {
            $list = $list->where('cate', $cate);
        }
        $list = $list->select();
        $user_id = $this->request->user_id ? $this->request->user_id : 0;
        $result = [];
        //全部产品
        $productss = (new Product())->alias('p')
            ->order(['p.sort' => 'desc', 'p.id' => 'desc'])
            ->leftjoin('cart c', ['c.user_id = ' . $user_id, 'c.productid = p.id'])
            ->where(['p.isdel' => 1, 'p.isremove' => 1, 'p.isshow' => 1, 'p.agentid' => $agentid])
            ->field('p.id,p.title,p.inventory,p.parame,p.descs,p.images,p.price,ifnull(c.id,0) as cartid,ifnull(c.number,0) as number')
            ->select();
        foreach ($productss as $product) {
            $product['parame'] = json_decode($product['parame'], true) ?? [];
        }
        $result[0] = [
            'id' => $cate - 9999999,
            'name' => '全部产品',
            'images' => '',
            'product' => $productss
        ];
        foreach ($list as $k => $row) {
            $row['product'] =  (new Product())->alias('p')
                ->order(['p.sort' => 'desc', 'p.id' => 'desc'])
                ->leftjoin('cart c', ['c.user_id = ' . $user_id, 'c.productid = p.id'])
                ->where(['p.isdel' => 1, 'p.isshow' => 1, 'p.isremove' => 1, 'p.agentid' => $agentid, 'p.cate' => $row['id']])
                ->field('p.id,p.title,p.inventory,p.parame,p.descs,p.images,p.price,ifnull(c.id,0) as cartid,ifnull(c.number,0) as number')
                ->select();
            foreach ($row['product'] as $product) {
                $product['parame'] = json_decode($product['parame'], true) ?? [];
            }
            $result[$k + 1] = $row;
        }
        $this->result($result, 0, '获取成功');
    }

    public function product()
    {
        $cate = $this->request->get('cate/d', 0);
        $ishot = $this->request->get('ishot/d', 1);
        $title = $this->request->get('title/s', '');
        $agentid = $this->request->user['agentid'];
        $page = $this->request->get('page/d', 1);
        $all = $this->request->get('all/d', 1);
        $limit = 15;
        $list =  (new Product())
            ->where(['isdel' => 1, 'isshow' => 1, 'isremove' => 1, 'agentid' => $agentid])
            ->field('id,title,images,price,descs,cate,subcate,inventory,parame');
        if ($all == 1) {
            $list = $list->limit($limit)->page($page);
        }
        if (!empty($cate)) {
            $list = $list->where('cate', $cate);
        }
        if (!empty($title)) {
            $list = $list->where('title', 'like', '%' . $title . '%');
        }
        if (!empty($ishot) && $ishot == 1) {
            $list = $list->order(['ishot' => 'desc']);
        } else if (!empty($ishot) && $ishot == 2) {
            $list = $list->where(['isnew' => 2]);
        } else {
            $list = $list->order(['title' => 'desc', 'sales' => 'desc', 'sort' => 'desc']);
        }
        if (!empty($subcate)) {
            if ($subcate < 0) {
                // $list = $list->where('cate', ($subcate + 9999999));
            } else {
                $list = $list->where('subcate', $subcate);
            }
        }
        $list = $list->order(['sales' => 'desc', 'sort' => 'desc'])->select();
        $user_id = $this->request->user_id ? $this->request->user_id : 0;
        foreach ($list as $product) {
            $cart = (new  Cart())->where(['user_id' => $user_id, 'productid' => $product['id']])->field('id,number')->find();
            $product['cartid'] = $cart['id'] ?? 0;
            $product['number'] = $cart['number'] ?? 0;
            $product['parame'] = json_decode($product['parame'], true) ?? [];
            try {
                if (!empty($product['images'])) {
                    $parsedUrl = parse_url($product['images']);
                    $filename = basename($product['images']);
                    $file = './yasuo/' . $filename;
                    if (!file_exists($file)) {
                        $image = \think\Image::open('.' . $parsedUrl['path']);
                        $sturl = './yasuo' . '/' . $filename;
                        $turl = '/yasuo' . '/' . $filename;
                        $image->thumb(750, 750)->save($sturl, 'jpeg', 70);
                        $product['images'] = "https://" . Env('app.api_url') . $turl;
                    } else {
                        $sturl = '/yasuo' . '/' . $filename;
                        $product['images'] = "https://" . Env('app.api_url') . $sturl;
                    }
                }
            } catch (\Exception $e) {
            }
        }
        $this->result($list, 0, '获取成功');
    }
}
